package org.elasticsearch;

import com.obs.services.ObsClient;
import org.elasticsearch.common.lease.Releasable;
import org.elasticsearch.common.util.concurrent.AbstractRefCounted;

import java.io.IOException;

/**
 * Handles the shutdown of the wrapped {@link ObsClient} using reference
 * counting
 */
public class ObsReference extends AbstractRefCounted implements Releasable {

    private final ObsClient client;

    ObsReference(ObsClient client) {
        super("HUAWEI_OBS_CLIENT");
        this.client = client;
    }

    /**
     * Call when the client is not needed anymore.
     */
    @Override
    public void close() {
        decRef();
    }

    /**
     * Returns the underlying `Huawei OBS` client. All method calls are permitted BUT
     * NOT shutdown. Shutdown is called when reference count reaches 0.
     */
    public ObsClient client() {
        return client;
    }

    @Override
    protected void closeInternal() {
        try {
            client.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

}
